/*
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-11-10 11:01:50
 * @LastEditTime: 2022-11-11 17:29:58
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description:
 */
(function () {
  const upload = document.querySelector("#upload1"),
    uploadInput = upload.querySelector(".upload_inp"),
    uploadSelect = upload.querySelector(".upload_button.select"),
    uploadBtn = upload.querySelector(".upload_button.upload"),
    uploadTip = upload.querySelector(".upload_tip"),
    uploadList = upload.querySelector(".upload_list");
  let file = null;
  //# 打开文件弹框
  uploadSelect.addEventListener("click", () => {
    uploadInput.click();
  });
  //# 选择文件
  uploadInput.addEventListener("change", () => {
    let tempFile = uploadInput.files[0];
    // 文件格式判断
    const fileFormat = /(PNG|JPG|JPEG)/i;
    if (!fileFormat.test(tempFile.type)) {
      alert("文件格式错误");
      return;
    }
    //文件大小判断
    const maxSize = 1024 * 1024 * 2;
    if (tempFile.size > maxSize) {
      alert("文件不能超过 2M");
      return;
    }
    file = tempFile;
    uploadTip.style.display = "none";
    uploadList.style.display = "block";
    uploadList.innerHTML = `
    <li>
      <span>文件：${file.name}</span>
      <span><em>移除</em></span>
    </li> 
    `;
    console.log("🚀 ~ file: upload.js ~ line 36 ~ uploadInput.addEventListener ~ file", file);
  });
  // #上传文件
  uploadBtn.addEventListener("click", async () => {
    if (!file) return alert("请上传文件");
    const fb = new FormData();
    fb.append("file", file);
    fb.append("filename", file.name);
    changeUploadStatus(true);
    await instance.post("/upload_single", fb);
    changeUploadStatus();
    clearFileList();
  });
  // #改变上传状态
  const changeUploadStatus = (status = false) => {
    if (status) {
      uploadSelect.classList.add("disable");
      uploadBtn.classList.add("loading");
    } else {
      uploadSelect.classList.remove("disable");
      uploadBtn.classList.remove("loading");
    }
  };

  //# 移除文件
  uploadList.addEventListener(
    "click",
    (e) => {
      console.log("🚀 ~ file: upload.js ~ line 43 ~ uploadList.addEventListener ~ e", e);
      if (e.target.tagName === "EM") {
        clearFileList();
      }
    },
    true
  );
  // #清空fileList
  const clearFileList = () => {
    uploadTip.style.display = "block";
    uploadList.style.display = "none";
    uploadList.innerHTML = "";
  };
})();
// base64 上传
(function () {
  const upload = document.querySelector("#upload2"),
    uploadInput = upload.querySelector(".upload_inp"),
    uploadSelect = upload.querySelector(".upload_button.select");

  let file = null;
  //# 打开文件弹框
  uploadSelect.addEventListener("click", () => {
    uploadInput.click();
  });
  // #解析 base64
  const generateBase64 = (file) => {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (e) => {
        resolve(e.target.result);
      };
    });
  };
  //# 选择文件
  uploadInput.addEventListener("change", async () => {
    let tempFile = uploadInput.files[0],
      base64;
    base64 = await generateBase64(tempFile);
    // 文件格式判断
    const fileFormat = /(PNG|JPG|JPEG)/i;
    if (!fileFormat.test(tempFile.type)) {
      alert("文件格式错误");
      return;
    }
    //文件大小判断
    const maxSize = 1024 * 1024 * 2;
    if (tempFile.size > maxSize) {
      alert("文件不能超过 2M");
      return;
    }
    file = tempFile;
    changeUploadStatus(true);
    await instance.post(
      "/upload_single_base64",
      {
        file: encodeURIComponent(base64),
        filename: file.name,
      },
      {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      }
    );
    changeUploadStatus();
  });
  // #改变上传状态
  const changeUploadStatus = (status = false) => {
    if (status) {
      uploadSelect.classList.add("disable");
    } else {
      uploadSelect.classList.remove("disable");
    }
  };
})();
//切片上传
(function () {
  const upload = document.querySelector("#upload7"),
    upload_inp = upload.querySelector(".upload_inp"),
    upload_select = upload.querySelector(".upload_button.select"),
    upload_progress = upload.querySelector(".upload_progress"),
    upload_progress_value = upload.querySelector(".value");
  let file = null;
  // #选择文件
  upload_select.addEventListener("click", () => {
    upload_inp.click();
  });
  // #文件转换
  const changeBuffer = (file) => {
    return new Promise((resolve) => {
      const rf = new FileReader();
      rf.readAsArrayBuffer(file);
      rf.onload = (e) => {
        // 获取 文件buffer
        let buffer = e.target.result,
          spark = new SparkMD5.ArrayBuffer(),
          //文件 hash
          HASH,
          //文件后缀
          suffix;
        spark.append(buffer);
        HASH = spark.end();
        suffix = /\.([a-zA-Z0-9]+)$/.exec(file.name)[1];
        resolve({
          buffer,
          HASH,
          filename: `${HASH}.${suffix}`,
          suffix,
        });
      };
    });
  };
  // #上传
  upload_inp.addEventListener("change", async () => {
    file = upload_inp.files[0];
    // 1.生成文件Buffer
    const { HASH, suffix } = await changeBuffer(file);
    // 2.获取已将上传的文件节点
    let already = [];
    const { fileList } = await instance.get("/upload_already", {
      params: HASH,
    });
    already = fileList;
    // 3.实现文件切片处理 「固定数量 & 固定大小」
    //切分最大数量
    const maxCount = 100;
    //切分体积
    let size = 1024 * 100,
      //切分数量
      count = Math.ceil(file.size / size),
      //索引
      index = 0,
      //上传切片数组
      chunks = [];
    //先按照固定大小进行切割，若大于最大数量则按照固定数量进行切割
    if (count > maxCount) {
      size = file.size / maxCount;
      count = maxCount;
    }
    // 4.生成切分文件
    do {
      chunks.push({
        filename: `${HASH}_${index + 1}.${suffix}`,
        file: file.slice(size * index, size * (index + 1)),
      });
      index++;
    } while (index < count);
    index = 0;

    // 5.上传文件
    chunks.forEach(async (chunk) => {
      if (already.length > 0 && already.includes(chunk.filename)) {
        complete();
        return;
      }
      const fb = new FormData();
      fb.append("file", chunk.file);
      fb.append("filename", chunk.filename);
      await instance.post("/upload_chunk", fb);
      // 判断是否可合并文件
      complete();
    });
    //6. 判断是否可合并文件
    const complete = async () => {
      index++;
      upload_select.classList.add("loading");
      upload_progress.style.display = "block";
      upload_progress_value.style.width = (index / count) * 100 + "%";
      if (index < count) return;
      await instance.post(
        "/upload_merge",
        {
          HASH,
          count,
        },
        {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        }
      );
      clear();
    };
    // 清空状态
    const clear = () => {
      upload_select.classList.remove("loading");
      upload_progress.style.display = "none";
      upload_progress_value.style.width = 0;
    };
  });
})();
